// pages/mine/index.js
const AV = require('../../sdk/av-core-min')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo:null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onShow(options) {
        console.log(getApp());
        let {userInfo} = getApp().globalData
        this.setData({userInfo})
    },
    handleSetting(){
        let {userInfo} = getApp().globalData
        if(userInfo){
            wx.navigateTo({
              url: '/pages/setting/index',
            })
            return
        }
        wx.showToast({
          title: '请登录后再操作',
          icon:'none'
        })
    },
    handleMineSearch(ev){
        // console.log('父级页面收到了子组件的值',ev);
        console.log('旧数据',getApp().globalData.myData);  //读取全局数据
        let {detail} = ev //获取子父通信数据
        getApp().globalData.myData = detail //修改全局数据
        console.log('新数据',getApp().globalData.myData);  
    },
    handleLogin(){
        // 方法2：使用leancloud体验真实授权登录流程
        AV.User.loginWithMiniApp().then(res=>{
            console.log(res);
            let {attributes,id,_sessionToken} = res
            attributes.id = id
            attributes.token = _sessionToken
            console.log(attributes);
            getApp().globalData.userInfo = attributes //全局存储
            wx.setStorage({
                key:'userInfo-2303',
                data:attributes
            })
            this.setData({userInfo:attributes})
        })
    },
    handleLogout(){
        this.setData({userInfo:null})
        getApp().globalData.userInfo = null
        wx.removeStorage({
          key: 'userInfo-2303',
        })
    },
    // 订阅消息
    handleSubscribe(){
        let {userInfo} = getApp().globalData
        if(!userInfo){
            wx.showToast({
              title: '请登录后再尝试订阅',
              icon:'none'
            })
            return
        }
        wx.requestSubscribeMessage({
          tmplIds: ['LV32oJ-ULXI6xB5Bc8qBBdK63FcU5sD7gZA7gLu7rKM'],
          success:(res)=>{
            console.log(res);
            let state = res['LV32oJ-ULXI6xB5Bc8qBBdK63FcU5sD7gZA7gLu7rKM']
            if(state=='accept'){
                //获取用户openid，发送给后端
                let {openid} = userInfo.authData.lc_weapp
                console.log(openid);
            }
          }
        })
    }
})